<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收费站" prop="deptId" v-if="deptId==101">
        <el-tree-select style="width: 100%;" v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
          value-key="id" placeholder="请选择" check-strictly />

      </el-form-item>

      <el-form-item label="日期" prop="happenTime">
        <el-date-picker clearable v-model="queryParams.happenTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择事件发生时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="特情类型" prop="special" v-if="type==1">
        <el-select style="width:100%" v-model="queryParams.special" placeholder="请选择特情类型" >
          <el-option v-for="dict in audit_special_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="特情类型" prop="special" v-if="type==2">
        <el-select style="width:100%" v-model="queryParams.special" placeholder="请选择特情类型" >
          <el-option v-for="dict in audit_exceed_special_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['audit:special:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['audit:special:export']">导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['audit:special:importData']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Menu" @click="handleStatistics">统计</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="specialList" @selection-change="handleSelectionChange" show-overflow-tooltip>

      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="收费站" align="center" prop="deptName" />
      <el-table-column label="特情类型" align="center" prop="special" v-if="type==1">
        <template #default="scope">
          <dict-tag :options="audit_special_type" :value="scope.row.special" />
        </template>
      </el-table-column>
      <el-table-column label="特情类型" align="center" prop="special" v-if="type==2">
        <template #default="scope">
          <dict-tag :options="audit_exceed_special_type" :value="scope.row.special" />
        </template>
      </el-table-column>
      <el-table-column label="辆次" align="center" prop="vehiclesNo" />
      <el-table-column label="是否存在问题" align="center" prop="isError">
        <template #default="scope">
          <dict-tag :options="audit_is_error" :value="scope.row.isError" />
        </template>
      </el-table-column>
      <el-table-column label="事件发生时间" align="center" prop="happenTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.happenTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" show-overflow-tooltip prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['audit:special:query']">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['audit:special:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['audit:special:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改特情稽核对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <div class="dialog-scroll">
        <el-form ref="specialRef" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收费站" prop="deptId">
                <el-tree-select style="width:100%" class="inputDeep" v-model="form.deptId" :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择收费站" check-strictly clearable
                  :disabled="isView" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="特情类型" prop="special" v-if="type==1">
                <el-select style="width:100%" class="inputDeep" v-model="form.special" placeholder="请选择特情类型" :disabled="isView">
                  <el-option v-for="dict in audit_special_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="特情类型" prop="special" v-if="type==2">
                
                <el-select style="width:100%" class="inputDeep" v-model="form.special" placeholder="请选择特情类型" :disabled="isView">
                  <el-option v-for="dict in audit_exceed_special_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="辆次" prop="vehiclesNo">
                <el-input style="width:100%" v-model="form.vehiclesNo" placeholder="请输入辆次" :disabled="isView" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="事件发生时间" prop="happenTime">
                <el-date-picker style="width:100%" clearable v-model="form.happenTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择事件发生时间"
                  :disabled="isView">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否存在问题" prop="isError">
                <el-radio-group v-model="form.isError" style="width:100%" :disabled="isView">
                  <el-radio v-for="dict in audit_is_error" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="问题描述" prop="errorDescribe">
                <Editor :modelValue="form.errorDescribe" v-model="form.errorDescribe" :minHeight="200" :disabled="isView" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="处理结果" prop="disposeResult">
                <Editor :modelValue="form.disposeResult" v-model="form.disposeResult" :minHeight="200" :disabled="isView" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isView" :rows="5"  />
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" v-if="!isView">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


     <!-- 用户导入对话框 -->
     <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <Statistics :tableData="tableData" :type="type" ref="statisticsRef" @changeType="handleStatistics" />
  </div>
</template>

<script setup name="Special">
import moment from "moment";
import { deptTreeSelect } from "@/api/system/user";
import { listSpecial, getSpecial, delSpecial, addSpecial, updateSpecial,postSpecialCountFee,postSpecialCountEx } from "@/api/charge/special";
import useUserStore from '@/store/modules/user'
import { getToken } from "@/utils/auth";
import Statistics from "./components/Statistics.vue";
import { getCKInfo } from '@/utils/auth'
const { proxy } = getCurrentInstance();
const { audit_special_type, audit_is_error,audit_exceed_special_type } = proxy.useDict('audit_special_type', 'audit_is_error','audit_exceed_special_type');
const route = useRoute();
const userStore = useUserStore()
const specialList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const type=ref(route.query.type)
const total = ref(0);
const title = ref("");
const deptOptions = ref([])
const deptId = ref(Number(getCKInfo('deptId')))
const isView = ref(false)
const tableData = ref([])
const statisticsRef = ref()
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/audit/special/importData"
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    menuType:route.query.type,
    deptId:deptId.value
  },
  rules: {
    deptId: [{ required: true, message: '收费站不能为空', trigger: 'blur' }],
    special: [{ required: true, message: '特情类型不能为空', trigger: 'blur' }],
    vehiclesNo: [{ required: true, message: '辆次不能为空', trigger: 'blur' }],
    happenTime: [{ required: true, message: '事件发生时间不能为空', trigger: 'blur' }],
    isError: [{ required: true, message: '是否存在问题不能为空', trigger: 'blur' }],
  }
});

const { queryParams, form, rules } = toRefs(data);

function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
/** 查询特情稽核列表 */
function getList() {
  loading.value = true;
  listSpecial(queryParams.value).then(response => {
    specialList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    menuType:route.query.type,
    deptId:deptId.value
  };
  proxy.resetForm("specialRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {

  proxy.resetForm("queryRef");
  queryParams.value = { pageNum: 1,pageSize: 10,menuType:route.query.type,
    deptId:deptId.value}
  queryParams.value.deptId = deptId.value;
  handleQuery();
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  isView.value = false;
  title.value = "添加特情处置";
  form.value.deptId = deptId.value;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSpecial(_id).then(response => {
    form.value = response.data;

    isView.value = false;
    title.value = "修改特情处置";
    open.value = true;
    form.value.special=response.data.special.toString();

  });
}
const handleView = (row) => {
  reset();
  const _id = row.id || ids.value
  getSpecial(_id).then(response => {
    form.value = response.data;
    form.value.special=response.data.special.toString();
    title.value = "查看特情处置";
    isView.value = true;
    open.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["specialRef"].validate(valid => {
    if (valid) {
      form.value.menuType=type.value;

      if (form.value.id != null) {
        updateSpecial(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSpecial(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除特情处置编号为"' + _ids + '"的数据项？').then(function () {
    return delSpecial(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('audit/special/export', {
    ...queryParams.value
  }, `特情处置_${new Date().getTime()}.xlsx`)
}
const getText = (text) => {
  if (!text) return "-"
  return text.replace(/<[^>]+>/g, "")
}
// const getDeptId = () => {
//   userStore.getInfo().then(res => {
//     if (res.code == 200) {
//       deptId.value = res.user.dept.deptId;
//       queryParams.value.deptId = deptId.value
//       getList()
//     }

//   })
// }
/** 导入按钮操作 */
function handleImport() {
  upload.title = "导入";
  upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/importTemplate/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
function handleStatistics(date) {
  // 本年  本季度  本月
  if (!date || !date.startDate) {
    date.startDate = moment().format('YYYY-MM-DD')
    date.endDate =moment().format('YYYY-MM-DD')
  }
  tableData.value=[]

  let urlArr=['',postSpecialCountFee,postSpecialCountEx]
  urlArr[Number(type.value)]({
    "startDate": date.startDate,
    "endDate": date.endDate,
    "menuType": type.value,
    deptId: deptId.value,
  
  }).then(res => {
    if (res.code == 200 && res.data) {
      tableData.value=res.data;
     
      statisticsRef.value.open();
    }
  })
}

// getDeptId()
getList()
getDeptTree()
</script>

<style scoped>
.text-hidden {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.dialog-scroll {
  height: 800px;
  overflow-x: hidden;
  overflow-y: scroll;
}

.inputDeep >>> .el-input__inner {
  min-height: 38px;
}
</style>
